package com.hicripps;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 一个简单的四则运算
 * 
 * 主要写了Button的OnClickListener的几种写法
 * 
 * @author yangjuntao@p-an.com 2013-12-2
 */
public class MainActivity extends Activity
{

	@Override
	protected void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 初始化
		result = (TextView) findViewById(R.id.result);
		a = (EditText) findViewById(R.id.a);
		b = (EditText) findViewById(R.id.b);

		// addition 内部匿名类
		Button add = (Button) findViewById(R.id.add);
		add.setOnClickListener(new Button.OnClickListener()
		{
			@Override
			public void onClick(final View v)
			{
				int ia = Integer.parseInt(a.getText().toString());
				int ib = Integer.parseInt(b.getText().toString());
				result.setText("加法" + (ia + ib));
			}
		});

		// subtraction 外部类实现
		Button sul = (Button) findViewById(R.id.sul);
		sul.setOnClickListener(new SubOnClickListener(this));

		// multiplication 其实和add是一个写法
		Button mul = (Button) findViewById(R.id.mul);
		mul.setOnClickListener(mulOnClickListener);

		// division 在activity_main.xml配置 + OnClick()方法
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	// //////
	OnClickListener mulOnClickListener = new OnClickListener()
	{

		@Override
		public void onClick(final View v)
		{
			int ia = Integer.parseInt(a.getText().toString());
			int ib = Integer.parseInt(b.getText().toString());
			result.setText("乘法" + (ia * ib));
		}
	};

	// ///////
	public void divOnClick(final View view)
	{
		int ia = Integer.parseInt(a.getText().toString());
		int ib = Integer.parseInt(b.getText().toString());
		result.setText("除法" + (ia / ib));
	}

	// ////////////////////////////
	private TextView result = null;
	private EditText a = null;
	private EditText b = null;

	public EditText getA()
	{
		return a;
	}

	public EditText getB()
	{
		return b;
	}

	public TextView getResult()
	{
		return result;
	}

}

class SubOnClickListener implements OnClickListener
{
	private final MainActivity activity;

	public SubOnClickListener(final MainActivity activity)
	{
		this.activity = activity;
	}

	@Override
	public void onClick(final View v)
	{
		int ia = Integer.parseInt(activity.getA().getText().toString());
		int ib = Integer.parseInt(activity.getB().getText().toString());
		activity.getResult().setText("减法" + (ia - ib));
	}

}